package cz.cvut.fit.mi_paa.knapsack.strategy;

import cz.cvut.fit.mi_paa.abs.Context;
import cz.cvut.fit.mi_paa.knapsack.KnapsackContext;
import cz.cvut.fit.mi_paa.knapsack.KnapsackInstance;
import cz.cvut.fit.mi_paa.knapsack.Item;

import java.io.FileWriter;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: milos
 * Date: 1.10.12
 * Time: 11:20
 * To change this template use File | Settings | File Templates.
 */
public class BruteForceKnapsackStrategy extends KnapsackStrategy {
    private long solution=-1L;
    private long iterations;
    private int solPrice;
    public BruteForceKnapsackStrategy(Context context) {
        super(context);
        this.iterations = (long) Math.pow(2, instance.getItemNumber());
    }

    @Override
    public void solve() throws IOException {
        Item[] items = instance.getItems();
        context.getSw().start();
        for(long i = 0; i< iterations;i++) {
            long shift = i;
            int price = 0;
            int weight = 0;
            for (int j = 0 ; j<instance.getItemNumber() ;j++)   {
                shift = (shift << 1);
                if(((shift & iterations) >> instance.getItemNumber()) == 1) {
                    Item item = items[j];
                    price += item.getPrice();
                    weight += item.getWeight();
                }

            }
            if(weight<= instance.getCapacity()) {
                if(price>solPrice) {solution = i;solPrice=price;}
            }
        }
        context.getSw().stop();
    }

    @Override
    public void writeResult() throws IOException {

        FileWriter resultWriter = context.getResultWriter();
        long shift = solution;
        resultWriter.write(instance.getId() + " ");
        resultWriter.write(context.getSw().getTimeMillis() + " ");
        resultWriter.write(instance.getItemNumber() + " ");
        resultWriter.write(solPrice+ "  ");
        for (int j = 0 ; j<instance.getItemNumber() ;j++)   {
            shift = (shift<<1);
            if(j<(instance.getItemNumber()-1))
                context.getResultWriter().write(((shift & iterations) >> instance.getItemNumber()) + " ");
            else
                context.getResultWriter().write(((shift & iterations) >> instance.getItemNumber()) + "\n");
        }
    }
}
